//
//  SameViewController.m
//  miaopai
//
//  Created by Crow Zhang on 15/11/12.
//  Copyright © 2015年 Crow Zhang. All rights reserved.
//

#import "SameViewController.h"
#import <CoreMotion/CoreMotion.h>
#import <CoreLocation/CoreLocation.h>
#import "MacroDefinition.h"
#import "CustomerNetworking.h"
#import "UIImageView+WebCache.h"
#import <AudioToolbox/AudioToolbox.h>
#import "Channel.h"
#import "SCCatWaitingHUD.h"
#import "TouchView.h"
#import "VideoDetailViewController.h"

@interface SameViewController ()<CLLocationManagerDelegate>

@property (nonatomic, retain) UILabel *temperature; // 温度
@property (nonatomic, retain) UILabel *weather; // 天气
@property (nonatomic, retain) UILabel *cityLabel; // 城市

@property (nonatomic, retain) UILabel *countLabel; // 摇一摇人数
@property (nonatomic, retain) UIImageView *titleImage; // 摇一摇的 image
@property (nonatomic ,retain) UILabel *titleLabel; // 摇一摇的 label
@property (nonatomic, retain) TouchView *backView; // 摇一摇改变的视图
@property (nonatomic, retain) CLLocationManager *locationManager; // 定位
@property (nonatomic, retain) CMMotionManager *motionManager; // 摇一摇

@end

@implementation SameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIBarButtonItem *backeItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
    self.title = @"摇一摇～";
    self.navigationItem.leftBarButtonItem = backeItem;
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"返回";
    self.navigationItem.backBarButtonItem = backItem;
    [backItem release];
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];

    [[UIApplication sharedApplication] setApplicationSupportsShakeToEdit:YES];
    [self becomeFirstResponder];

//    创建一个视图
    [self creatViews];

//    开启定位
    [self getcurLocation];
}
#pragma mark - 创建视图
- (void)creatViews{

    self.backView = [[TouchView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * 0.8, SCREEN_WIDTH )];
    _backView.center = CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT * 0.7 - 50);
    self.backView.backgroundColor = [UIColor whiteColor];
    [self.backView addMyTarget:self action:@selector(toView:)];
    [self.view addSubview:_backView];
    [_backView release];

    self.titleImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _backView.Width, _backView.Height * 0.8)];
    _titleImage.userInteractionEnabled = YES;
    self.titleImage.backgroundColor = [UIColor whiteColor];
    [_backView addSubview:_titleImage];
    [_titleImage release];

//    self.countLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, _titleImage.Y + _titleImage.Height , _backView.Width, _backView.Height * 0.1)];
    _countLabel.backgroundColor = [UIColor greenColor];
    _countLabel.userInteractionEnabled = YES;
    [_backView addSubview:_countLabel];
    [_countLabel release];

    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, _titleImage.Y + _titleImage.Height, _backView.Width, _backView.Height * 0.1)];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.text = @"摇一摇更精彩";
    _titleLabel.backgroundColor = [UIColor whiteColor];
    _titleImage.userInteractionEnabled = YES;
    [_backView addSubview:_titleLabel];
    [_titleLabel release];

    self.cityLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 84, SCREEN_WIDTH, 30)];
//    self.cityLabel.backgroundColor = [UIColor cyanColor];
    self.cityLabel.text = @"城市";
    _cityLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_cityLabel];
    [_cityLabel release];

    self.weather = [[UILabel alloc] initWithFrame:CGRectMake(0 , _cityLabel.Y + 30, _cityLabel.Width , _cityLabel.Height)];
//    self.weather.backgroundColor = [UIColor cyanColor];
    self.weather.text = @"天气";
    _weather.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_weather];
    [_weather release];

    self.temperature = [[UILabel alloc] initWithFrame:CGRectMake(0, _weather.Y + 30, _weather.Width , _weather.Height)];
//    self.temperature.backgroundColor = [UIColor cyanColor];
    self.temperature.text = @"温度";
    _temperature.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_temperature];
    [_temperature release];
}

#pragma mark - 定位
#pragma mark开始定位
//    获取当前用户位置
- (void)getcurLocation{
    if (_locationManager == nil) {
        self.locationManager = [[CLLocationManager alloc] init];
    }
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager.delegate = self;
        //        设置为最佳准确度
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;

        //        请求用户授权
        [self.locationManager requestAlwaysAuthorization];

        //        开始定位
        [self.locationManager startUpdatingLocation];

        //        停止定位
        //        [self.locationManager stopUpdatingLocation];
    }
}
#pragma mark 代理
//    获取当前位置信息
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    CLLocation *location = locations.lastObject;

    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    
    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {

            NSDictionary *test = [placemark addressDictionary];
            //  Country(国家)  State(城市)  SubLocality(区)
            NSLog(@"%@", test);
            NSString *city = [test objectForKey:@"City"];
            NSLog(@"%@", city);
            if ([city hasSuffix:@"市"]) {
                city = [city substringToIndex:city.length - 1];
                NSLog(@"%@", city);
            }
            [self getWeatherDataByCity:city];
        }
    }];


    [self.locationManager stopUpdatingLocation];
}

- (void)getWeatherDataByCity:(NSString *)city {

    NSString *cityName = [NSString stringWithFormat:@"http://api.k780.com:88/?app=weather.future&weaid=%@&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json", city];
    cityName = [cityName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [CustomerNetworking customerConnectWithURL:cityName andparameters:nil andBlock:^(id response) {
        NSArray *array = [response objectForKey:@"result"];
        NSDictionary *dic = [array firstObject];
        self.cityLabel.text = [dic objectForKey:@"citynm"];
        self.weather.text = [dic objectForKey:@"weather"];
        self.temperature.text = [dic objectForKey:@"temperature"];
    }];
}

//-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
//
//    [_locationManager stopUpdatingLocation];
//    NSLog(@"location ok");
//
//    NSLog(@"%@",[NSString stringWithFormat:@"经度:%3.5f\n纬度:%3.5f",newLocation.coordinate.latitude,newLocation.coordinate.longitude]);
//
//    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
//    [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
//        for (CLPlacemark * placemark in placemarks) {
//
//            NSDictionary *test = [placemark addressDictionary];
//            //  Country(国家)  State(城市)  SubLocality(区)
//            NSLog(@"---------------------------------%@", [test objectForKey:@"State"]);
//        }
//    }];
//    
//}

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    [[SCCatWaitingHUD sharedInstance] animateWithInteractionEnabled:YES];
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    [CustomerNetworking customerConnectWithURL:[NSString stringWithFormat:@"http://api.miaopai.com/m/samecity.json?os=ios&page=1&per=20&unique_id=d148d7c2b9c27f685d9be7639517be5e3661826668&version=6.2.1" ] andparameters:nil andBlock:^(id response) {
        [[SCCatWaitingHUD sharedInstance] stop];
        NSArray *array = [response objectForKey:@"result"];

            NSInteger index = arc4random() % (array.count - 1);
        Channel *channel = [Channel channelWithDic:[[array objectAtIndex:index] objectForKey:@"channel"]];
            [self.titleImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", channel.pic.base, channel.pic.m]] placeholderImage:[UIImage imageNamed:@"zhanweitu.png"]];
        self.backView.channel = channel;
        self.titleLabel.text = channel.ext.t;
    }];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)dealloc
{
    [_temperature release];
    [_cityLabel release];
    [_weather release];
    [_countLabel release];
    [_titleImage release];
    [_titleLabel release];
    [_backView release];
    [_locationManager release];
    [super dealloc];
}

- (void)back:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)toView:(TouchView *)view
{
    if (view.channel != nil) {
        VideoDetailViewController *videoView = [[VideoDetailViewController alloc] init];
        videoView.scid = view.channel.scid;
        [self.navigationController pushViewController:videoView animated:YES];
        [videoView release];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
